package com.newidea.facillty.utils;

import com.intelligt.modbus.jlibmodbus.Modbus;
import com.intelligt.modbus.jlibmodbus.exception.ModbusIOException;
import com.intelligt.modbus.jlibmodbus.master.ModbusMaster;
import com.intelligt.modbus.jlibmodbus.master.ModbusMasterFactory;
import com.intelligt.modbus.jlibmodbus.tcp.TcpParameters;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class ModbusUtil {

    /**
     * 创建ModbusMasterTCP连接
     *
     * @param host 主机地址
     * @return ModbusMaster
     * @throws UnknownHostException 未找到主机异常
     */
    public static ModbusMaster createModbusMasterTCP(String host, int tcpPort)
        throws UnknownHostException, ModbusIOException {
        // 设置tcp参数
        TcpParameters tcpParameters = new TcpParameters();
        tcpParameters.setHost(InetAddress.getByName(host));
        tcpParameters.setKeepAlive(true);
        tcpParameters.setPort(tcpPort);

        // 创建Master节点
        ModbusMaster master = ModbusMasterFactory.createModbusMasterTCP(tcpParameters);
        // 设TransactionId自动增加
        Modbus.setAutoIncrementTransactionId(true);

        master.setResponseTimeout(10000);
        // 开启连接
        if (!master.isConnected()) {
            master.connect();
        }
        return master;
    }
}
